<template>
  <div class="document-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>加载中...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <!-- 文档不存在 -->
    <div v-if="!loading && !document" class="not-found">
      <h2>文档不存在或已被删除</h2>
      <router-link to="/documents" class="btn-back">返回文档列表</router-link>
    </div>
    
    <!-- 文档详情 -->
    <div v-if="document" class="document-content">
      <!-- 文档头部信息 -->
      <div class="document-header">
        <div class="document-title-section">
          <h1>{{ document.title || document.fileName }}</h1>
          <span :class="['status', document.status ? document.status.toLowerCase() : '']">
            {{ getStatusText(document.status) }}
          </span>
        </div>
        
        <div class="document-meta">
          <p>
            <strong>上传时间：</strong> {{ formatDate(document.createdAt) }}
          </p>
          <p>
            <strong>文件大小：</strong> {{ formatFileSize(document.fileSize) }}
          </p>
          <p v-if="document.pageCount">
            <strong>页数：</strong> {{ document.pageCount }} 页
          </p>
        </div>
        
        <div class="document-summary-section" v-if="document.processed">
          <div class="summary-header">
            <h3>文档摘要</h3>
            <div class="summary-actions">
              <button 
                v-if="documentSummary" 
                @click="summaryExpanded = !summaryExpanded" 
                class="btn-toggle-summary"
              >
                {{ summaryExpanded ? '收起' : '展开' }}
              </button>
              <button 
                @click="generateSummary" 
                class="btn-generate-summary"
                :disabled="generatingSummary"
              >
                {{ generatingSummary ? '生成中...' : (documentSummary ? '重新生成' : '生成摘要') }}
              </button>
            </div>
          </div>
          
          <div v-if="generatingSummary" class="summary-loading">
            <p>正在使用通义千问 Qwen-Long 模型生成摘要，请稍候...</p>
          </div>
          
          <div v-else-if="documentSummary" class="summary-content" :class="{ 'collapsed': !summaryExpanded }">
            <p>{{ documentSummary }}</p>
          </div>
          
          <div v-else-if="summaryError" class="summary-error">
            <p>{{ summaryError }}</p>
          </div>
          
          <div v-else class="summary-empty">
            <p>点击"生成摘要"按钮，使用通义千问 Qwen-Long 模型生成文档摘要</p>
          </div>
        </div>
        
        <div class="document-description" v-if="document.description">
          <h3>文档描述</h3>
          <p>{{ document.description }}</p>
        </div>
        
        <div class="document-actions">
          <button 
            v-if="document.status === 'UPLOADED'" 
            @click="processDocument" 
            class="btn-process"
            :disabled="processing"
          >
            {{ processing ? '处理中...' : '处理文档' }}
          </button>
          
          <button @click="showEditModal = true" class="btn-edit">
            编辑信息
          </button>
          
          <button 
            v-if="document.status === 'processed'" 
            @click="generateLearningPath" 
            class="btn-generate-path"
            :disabled="generatingPath"
          >
            <span v-if="generatingPath">
              <span class="spinner-small"></span>
              生成学习路径中...
            </span>
            <span v-else>生成学习路径</span>
          </button>
          
          <button 
            v-if="document.status === 'processed'" 
            @click="viewCards" 
            class="btn-view-cards"
          >
            查看知识卡片
          </button>
          
          <button 
            v-if="document.status === 'processed'" 
            @click="viewExercises" 
            class="btn-view-exercises"
          >
            查看练习题
          </button>
          
          <button @click="confirmDelete" class="btn-delete">
            删除文档
          </button>
        </div>
      </div>
      
      <!-- 文档内容区域 -->
      <div class="document-body">
        <!-- 章节导航 -->
        <div class="document-nav">
          <h3>章节</h3>
          <div v-if="loading" class="loading-chapters">加载章节中...</div>
          <div v-else-if="!chapters.length" class="no-chapters">暂无章节信息</div>
          <ul v-else class="chapter-list">
            <li 
              v-for="chapter in chapters" 
              :key="chapter.id"
              :class="{ active: selectedChapter && selectedChapter.value === chapter.id }"
              @click="selectChapter(chapter.id)"
            >
              {{ chapter.title }}
              <span class="card-count">{{ chapter.cardCount || 0 }}张卡片</span>
            </li>
          </ul>
        </div>
        
        <!-- 卡片列表 -->
        <div class="cards-container">
          <div class="cards-header">
            <h2>知识卡片</h2>
            <div class="cards-filter">
              <select v-model="difficultyFilter" class="filter-select">
                <option value="">所有难度</option>
                <option value="1">简单</option>
                <option value="2">中等</option>
                <option value="3">困难</option>
              </select>
              
              <input 
                type="text" 
                v-model="searchQuery" 
                placeholder="搜索卡片..." 
                class="search-input"
              />
            </div>
          </div>
          
          <div v-if="loadingCards" class="loading-cards">
            <p>加载卡片中...</p>
          </div>
          
          <div v-else-if="!cards.length" class="no-cards">
            <p v-if="document && !document.processed">文档尚未处理，请先处理文档生成知识卡片</p>
            <p v-else-if="document && document.processingStatus === 'processing'">文档正在处理中，请稍后查看</p>
            <p v-else-if="document && document.processingStatus === 'failed'">
              文档处理失败，请重试
              <button 
                @click="reprocessDocument" 
                class="btn-reprocess"
                :disabled="processing"
              >
                {{ processing ? '处理中...' : '从失败处继续处理' }}
              </button>
            </p>
            <p v-else>暂无知识卡片</p>
          </div>
          
          <div v-else class="card-list">
            <div 
              v-for="card in filteredCards" 
              :key="card._id" 
              class="card-item"
              :class="{ 'card-bookmarked': isBookmarked(card._id) }"
            >
              <div class="card-header">
                <span :class="['difficulty', getDifficultyClass(card.difficulty)]">
                  {{ getDifficultyText(card.difficulty) }}
                </span>
                
                <button 
                  @click="toggleBookmark(card._id)" 
                  class="btn-bookmark"
                  :title="isBookmarked(card._id) ? '取消收藏' : '收藏'"
                >
                  <span v-if="isBookmarked(card._id)">★</span>
                  <span v-else>☆</span>
                </button>
              </div>
              
              <div class="card-content">
                <h3>{{ card.title }}</h3>
                <p>{{ card.content }}</p>
              </div>
              
              <div class="card-footer">
                <router-link :to="`/cards/${card._id}`" class="btn-view-card">
                  查看详情
                </router-link>
                
                <button @click="generateExercise(card._id)" class="btn-generate-exercise">
                  生成练习
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 编辑文档信息对话框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <h2>编辑文档信息</h2>
        
        <form @submit.prevent="updateDocument">
          <div class="form-group">
            <label for="title">标题</label>
            <input 
              type="text" 
              id="title" 
              v-model="editForm.title" 
              placeholder="文档标题"
            />
          </div>
          
          <div class="form-group">
            <label for="description">描述</label>
            <textarea 
              id="description" 
              v-model="editForm.description" 
              placeholder="文档描述"
              rows="4"
            ></textarea>
          </div>
          
          <div class="modal-actions">
            <button type="button" @click="showEditModal = false" class="btn-cancel">
              取消
            </button>
            <button type="submit" class="btn-save">
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 确认删除对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="modal-content">
        <h2>确认删除</h2>
        <p>确定要删除文档 "{{ document?.title || document?.fileName }}" 吗？</p>
        <p class="warning">此操作不可撤销，相关的知识卡片和练习题也将被删除。</p>
        
        <div class="modal-actions">
          <button @click="showDeleteConfirm = false" class="btn-cancel">取消</button>
          <button @click="deleteDocument" class="btn-confirm-delete">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useDocumentStore } from '@/store/document';
import { useUserStore } from '@/store/user';
import { cardApi, exerciseApi, documentApi, learningPathApi } from '@/services/api';
import { useToast } from 'vue-toastification';

const route = useRoute();
const router = useRouter();
const documentStore = useDocumentStore();
const userStore = useUserStore();
const toast = useToast();

// 状态变量
const document = ref(null);
const loading = ref(true);
const error = ref(null);
const cards = ref([]);
const loadingCards = ref(false);
const exercises = ref([]);
const loadingExercises = ref(false);
const showDeleteConfirm = ref(false);
const documentContent = ref('');
const loadingContent = ref(false);
const contentError = ref('');
const documentSummary = ref('');
const generatingSummary = ref(false);
const summaryError = ref('');
const summaryExpanded = ref(false);
const chapters = ref([]);
const selectedChapter = ref(null);
const difficultyFilter = ref('');
const searchQuery = ref('');
const showEditModal = ref(false);
const processing = ref(false);

// 学习路径相关状态变量
const generatingPath = ref(false);

// 计算属性
const filteredCards = computed(() => {
  let result = cards.value;
  
  // 按章节筛选
  if (selectedChapter.value) {
    result = result.filter(card => card.chapter === selectedChapter.value);
  }
  
  // 按难度筛选
  if (difficultyFilter.value) {
    // 检查difficulty是数字还是字符串
    if (typeof cards.value[0]?.difficulty === 'number') {
      // 如果是数字，转换筛选值为数字
      const numericDifficulty = parseInt(difficultyFilter.value, 10);
      result = result.filter(card => card.difficulty === numericDifficulty);
    } else {
      // 如果是字符串，直接比较
      result = result.filter(card => card.difficulty === difficultyFilter.value);
    }
  }
  
  // 按搜索关键词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(card => 
      card.title.toLowerCase().includes(query) || 
      card.content.toLowerCase().includes(query)
    );
  }
  
  return result;
});

// 获取文档详情
const fetchDocument = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    const response = await documentApi.getById(route.params.id);
    document.value = response.data;
    
    // 如果文档已处理，获取卡片和章节
    if (document.value.processed) {
      fetchCards();
      fetchChapters();
    }
    
  } catch (err) {
    console.error('获取文档详情失败:', err);
    error.value = '获取文档详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 获取文档卡片
const fetchCards = async () => {
  if (!document.value) return;
  
  console.log(`[fetchCards] 开始获取文档 ${document.value._id} 的卡片`);
  console.log(`[fetchCards] 文档状态: processed=${document.value.processed}, processingStatus=${document.value.processingStatus}`);
  
  loadingCards.value = true;
  
  try {
    console.log(`[fetchCards] 调用 documentApi.getDocumentCards 获取卡片`);
    // 直接使用 API 服务而不是 store
    const response = await documentApi.getDocumentCards(document.value._id);
    console.log(`[fetchCards] API 响应:`, response);
    
    cards.value = response.data;
    console.log(`[fetchCards] 成功获取到 ${cards.value.length} 张卡片`);
    
    // 获取用户书签，确保可以正确显示收藏状态
    if (userStore.isAuthenticated) {
      await userStore.fetchBookmarks();
      console.log(`[fetchCards] 已获取用户书签，共 ${userStore.bookmarks.length} 个`);
    }
  } catch (err) {
    console.error('[fetchCards] 获取卡片失败:', err);
    toast.error(`获取卡片失败: ${err.message || '未知错误'}`);
  } finally {
    loadingCards.value = false;
  }
};

// 获取文档章节
const fetchChapters = async () => {
  if (!document.value) return;
  
  try {
    const response = await cardApi.getChapters(document.value._id);
    chapters.value = response.data;
  } catch (err) {
    console.error('获取章节失败:', err);
  }
};

// 处理文档
const processDocument = async () => {
  if (!document.value) return;
  
  processing.value = true;
  
  try {
    await documentApi.process(document.value._id);
    toast.success('文档处理请求已提交，处理完成后将自动更新');
    
    // 轮询检查文档处理状态
    checkProcessingStatus();
  } catch (err) {
    console.error('处理文档失败:', err);
    toast.error('处理文档失败，请稍后重试');
    processing.value = false;
  }
};

// 检查文档处理状态
const checkProcessingStatus = async () => {
  const checkInterval = setInterval(async () => {
    try {
      const response = await documentApi.getById(document.value._id);
      const updatedDoc = response.data;
      
      document.value = updatedDoc;
      
      if (updatedDoc.processed) {
        clearInterval(checkInterval);
        processing.value = false;
        toast.success('文档处理完成');
        
        // 获取卡片和章节
        fetchCards();
        fetchChapters();
      } else if (updatedDoc.processingStatus === 'failed') {
        clearInterval(checkInterval);
        processing.value = false;
        toast.error('文档处理失败');
      }
    } catch (err) {
      console.error('检查处理状态失败:', err);
    }
  }, 1000*60); // 每5秒检查一次
};

// 从失败的地方继续处理文档
const reprocessDocument = async () => {
  if (!document.value) return;
  
  processing.value = true;
  
  try {
    console.log(`[DocumentDetailView] 从失败处继续处理文档 ${document.value._id}`);
    await documentApi.reprocess(document.value._id);
    toast.success('文档处理请求已提交，将从失败的地方继续处理');
    
    // 轮询检查文档处理状态
    checkProcessingStatus();
  } catch (err) {
    console.error('[DocumentDetailView] 重新处理文档失败:', err);
    toast.error(`重新处理文档失败: ${err.message || '未知错误'}`);
    processing.value = false;
  }
};

// 生成摘要
const generateSummary = async () => {
  if (!document.value) return;
  
  generatingSummary.value = true;
  summaryError.value = '';
  
  try {
    const response = await documentApi.getDocumentSummary(document.value._id);
    documentSummary.value = response.data.summary;
    
    // 如果是从缓存获取的，显示提示
    if (response.data.fromCache) {
      toast.info('摘要已从缓存加载');
    } else {
      toast.success('摘要生成成功');
    }
  } catch (err) {
    console.error('生成摘要失败:', err);
    summaryError.value = '生成摘要失败，请稍后重试';
  } finally {
    generatingSummary.value = false;
  }
};

// 生成学习路径
const generateLearningPath = async () => {
  if (!document.value) return;
  
  console.log(`[DocumentDetailView] 开始为文档 ${document.value._id} 生成学习路径`);
  generatingPath.value = true;
  
  try {
    console.log(`[DocumentDetailView] 调用 learningPathApi.generateLearningPath`);
    const response = await learningPathApi.generateLearningPath(document.value._id);
    console.log(`[DocumentDetailView] 生成学习路径响应:`, response.data);
    
    // 生成成功，显示成功提示
    toast.success('学习路径生成成功！', {
      position: 'top-right',
      timeout: 3000
    });
    
    // 跳转到学习路径详情页
    router.push(`/learning-paths/${response.data.learningPath._id}`);
  } catch (err) {
    console.error('[DocumentDetailView] 生成学习路径失败:', err);
    toast.error(err.response?.data?.message || '生成学习路径失败，请稍后重试', {
      position: 'top-right',
      timeout: 5000
    });
  } finally {
    generatingPath.value = false;
  }
};

// 查看卡片
const viewCards = () => {
  router.push(`/cards?documentId=${document.value._id}`);
};

// 查看练习题
const viewExercises = () => {
  router.push(`/exercises?documentId=${document.value._id}`);
};

// 确认删除
const confirmDelete = () => {
  showDeleteConfirm.value = true;
};

// 删除文档
const deleteDocument = async () => {
  if (!document.value) return;
  
  try {
    await documentApi.delete(document.value._id);
    toast.success('文档删除成功');
    router.push('/documents');
  } catch (err) {
    console.error('删除文档失败:', err);
    toast.error('删除文档失败，请稍后重试');
  } finally {
    showDeleteConfirm.value = false;
  }
};

// 选择章节
const selectChapter = (chapterId) => {
  if (selectedChapter.value === chapterId) {
    selectedChapter.value = null;
  } else {
    selectedChapter.value = chapterId;
  }
};

// 收藏卡片
const toggleBookmark = async (cardId) => {
  try {
    if (isBookmarked(cardId)) {
      await userStore.removeBookmark(cardId);
      toast.success('已取消收藏');
    } else {
      await userStore.addBookmark(cardId);
      toast.success('已添加收藏');
    }
  } catch (err) {
    console.error('操作收藏失败:', err);
    toast.error('操作失败，请稍后重试');
  }
};

// 检查卡片是否已收藏
const isBookmarked = (cardId) => {
  console.log(`[isBookmarked] 检查卡片 ${cardId} 是否已收藏`);
  console.log(`[isBookmarked] 当前书签列表:`, userStore.bookmarks);
  
  if (!userStore.bookmarks || userStore.bookmarks.length === 0) {
    console.log(`[isBookmarked] 书签列表为空，卡片 ${cardId} 未收藏`);
    return false;
  }
  
  const found = userStore.bookmarks.some(bookmark => bookmark.cardId === cardId);
  console.log(`[isBookmarked] 卡片 ${cardId} ${found ? '已收藏' : '未收藏'}`);
  return found;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B';
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;
  let size = bytes;
  
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024;
    i++;
  }
  
  return `${size.toFixed(2)} ${units[i]}`;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'uploaded': '已上传',
    'processing': '处理中',
    'processed': '已处理',
    'error': '处理失败'
  };
  
  return statusMap[status?.toLowerCase()] || status;
};

// 获取难度文本
const getDifficultyText = (difficulty) => {
  // 处理数字类型的难度
  if (typeof difficulty === 'number') {
    const numericDifficultyMap = {
      1: '简单',
      2: '中等',
      3: '困难'
    };
    return numericDifficultyMap[difficulty] || `难度${difficulty}`;
  }
  
  // 处理字符串类型的难度
  const stringDifficultyMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难'
  };
  
  return stringDifficultyMap[difficulty] || difficulty || '未知';
};

// 获取难度类名
const getDifficultyClass = (difficulty) => {
  // 处理数字类型的难度
  if (typeof difficulty === 'number') {
    const numericDifficultyMap = {
      1: 'easy',
      2: 'medium',
      3: 'hard'
    };
    return numericDifficultyMap[difficulty] || '';
  }
  
  // 处理字符串类型的难度
  return difficulty ? difficulty.toLowerCase() : '';
};

// 生命周期钩子
onMounted(async () => {
  // 获取文档详情
  await fetchDocument();
  
  // 如果文档已处理且有摘要，直接显示摘要
  if (document.value && document.value.processed && document.value.summary) {
    documentSummary.value = document.value.summary;
  }
  
  // 获取用户收藏
  await userStore.fetchBookmarks();
});
</script>

<style scoped>
.document-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.loading-container, .not-found {
  text-align: center;
  padding: 3rem;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.btn-back {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  background-color: #4CAF50;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  margin-top: 1rem;
}

/* 文档头部样式 */
.document-header {
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #eee;
}

.document-title-section {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.document-title-section h1 {
  margin: 0;
  color: #333;
}

.status {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.status.uploaded {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status.processing {
  background-color: #fff8e1;
  color: #ff8f00;
}

.status.processed {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status.error {
  background-color: #ffebee;
  color: #c62828;
}

.document-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  margin-bottom: 1rem;
  color: #666;
}

.document-summary-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border-left: 4px solid #4caf50;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.summary-header h3 {
  margin: 0;
  color: #333;
}

.summary-actions {
  display: flex;
  gap: 0.5rem;
}

.btn-toggle-summary {
  padding: 6px 12px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-toggle-summary:hover {
  background-color: #0d8aee;
}

.btn-generate-summary {
  padding: 6px 12px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-generate-summary:hover {
  background-color: #0d8aee;
}

.btn-generate-summary:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.summary-loading {
  padding: 10px;
  color: #666;
  font-style: italic;
}

.summary-content {
  padding: 10px;
  line-height: 1.6;
  color: #333;
  white-space: pre-line;
}

.summary-content.collapsed {
  max-height: 3em; /* 约2行文字的高度 */
  overflow: hidden;
  position: relative;
}

.summary-content.collapsed::after {
  content: "...";
  position: absolute;
  bottom: 0;
  right: 10px;
  background: linear-gradient(to right, transparent, #f9f9f9 50%);
  padding-left: 20px;
}

.summary-error {
  padding: 10px;
  color: #f44336;
}

.summary-empty {
  padding: 10px;
  color: #757575;
  font-style: italic;
}

.document-description {
  margin-bottom: 1.5rem;
}

.document-description h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #444;
  font-size: 1.1rem;
}

.document-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin: 1.5rem 0;
}

.btn-process,
.btn-edit,
.btn-delete {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}

.btn-process {
  background-color: #FF9800;
  color: white;
  border: none;
}

.btn-process:hover {
  background-color: #F57C00;
}

.btn-process:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

.btn-edit {
  background-color: #2196F3;
  color: white;
  border: none;
}

.btn-edit:hover {
  background-color: #1976D2;
}

.btn-delete {
  background-color: transparent;
  color: #F44336;
  border: 1px solid #F44336;
}

.btn-delete:hover {
  background-color: #ffebee;
}

.btn-generate-path {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.8rem 1.2rem;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-generate-path:hover {
  background-color: #45a049;
}

.btn-generate-path:disabled {
  background-color: #a5d6a7;
  cursor: not-allowed;
}

.spinner-small {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
}

/* 文档内容区域样式 */
.document-body {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 2rem;
}

/* 章节导航样式 */
.document-nav {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
}

.document-nav h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #444;
}

.loading-chapters, .no-chapters {
  color: #666;
  font-size: 0.9rem;
}

.chapter-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.chapter-list li {
  padding: 0.75rem;
  border-radius: 4px;
  margin-bottom: 0.5rem;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chapter-list li:hover {
  background-color: #f0f0f0;
}

.chapter-list li.active {
  background-color: #e8f5e9;
  color: #2e7d32;
  font-weight: 500;
}

.card-count {
  font-size: 0.8rem;
  color: #666;
}

/* 卡片列表样式 */
.cards-container {
  flex: 1;
}

.cards-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.cards-header h2 {
  margin: 0;
  color: #444;
}

.cards-filter {
  display: flex;
  gap: 1rem;
}

.filter-select, .search-input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.search-input {
  width: 200px;
}

.loading-cards, .no-cards {
  text-align: center;
  padding: 3rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #666;
}

.card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
}

.card-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1.5rem;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.card-item.card-bookmarked {
  border-color: #FFD700;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.difficulty {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.difficulty.easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty.medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty.hard {
  background-color: #ffebee;
  color: #c62828;
}

.btn-bookmark {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #FFD700;
}

.card-content {
  flex: 1;
}

.card-content h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #333;
  font-size: 1.1rem;
}

.card-content p {
  color: #555;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  gap: 0.75rem;
  margin-top: auto;
}

.btn-view-card, .btn-generate-exercise {
  padding: 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  text-align: center;
  flex: 1;
}

.btn-view-card {
  background-color: #2196F3;
  color: white;
  text-decoration: none;
  border: none;
}

.btn-view-card:hover {
  background-color: #1976D2;
}

.btn-generate-exercise {
  background-color: #FF9800;
  color: white;
  border: none;
}

.btn-generate-exercise:hover {
  background-color: #F57C00;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-cancel,
.btn-save,
.btn-confirm-delete {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
}

.btn-cancel {
  background-color: transparent;
  color: #333;
  border: 1px solid #ddd;
}

.btn-save {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.btn-confirm-delete {
  background-color: #F44336;
  color: white;
  border: none;
}

.warning {
  color: #F44336;
  font-weight: 500;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .document-body {
    grid-template-columns: 1fr;
  }
  
  .document-nav {
    margin-bottom: 1.5rem;
  }
  
  .cards-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .cards-filter {
    width: 100%;
  }
  
  .search-input {
    flex: 1;
  }
}

.btn-reprocess {
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  margin-top: 10px;
  cursor: pointer;
  font-weight: 500;
  display: block;
  transition: background-color 0.3s;
}

.btn-reprocess:hover {
  background-color: #f57c00;
}

.btn-reprocess:disabled {
  background-color: #ffcc80;
  cursor: not-allowed;
}
</style> 